<!DOCTYPE html>
<html lang="zh-CN">
  <head>
    <meta charset="UTF-8" />
    <title>文件上传方式示例</title>
  </head>
  <body>
    <h1>📤 文件上传方式演示</h1>

    <hr />
    <h2>① multipart/form-data 上传</h2>
    <form action="http://localhost:10086/upload-form" method="POST" enctype="multipart/form-data">
      <input type="file" name="file" />
      <input type="submit" value="表单方式上传" />
    </form>

    <h3>或使用 JS + FormData 上传</h3>
    <input type="file" id="formFile" />
    <button onclick="uploadFormData()">JS 上传 (multipart/form-data)</button>

    <hr />
    <h2>② application/octet-stream 上传</h2>
    <input type="file" id="rawFile" />
    <button onclick="uploadOctet()">JS 上传 (octet-stream)</button>

    <hr />
    <h2>③ application/x-www-form-urlencoded 上传（模拟文本）</h2>
    <input type="text" id="fileName" placeholder="文件名" value="example.txt" />
    <textarea id="fileContent" placeholder="文件内容">Hello, this is file content!</textarea><br />
    <button onclick="uploadUrlEncoded()">模拟文本上传</button>

    <script>
      function uploadFormData() {
        const file = document.getElementById('formFile').files[0]
        if (!file) return alert('请选择文件')
        const formData = new FormData()
        formData.append('file', file)

        fetch('http://localhost:10086/upload-form', {
          method: 'POST',
          body: formData
        })
          .then((res) => res.text())
          .then(alert)
          .catch((err) => alert('上传失败: ' + err))
      }

      function uploadOctet() {
        const file = document.getElementById('rawFile').files[0]
        if (!file) return alert('请选择文件')

        fetch('http://localhost:10086/upload', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/octet-stream',
            'X-Filename': file.name
          },
          body: file
        })
          .then((res) => res.text())
          .then(alert)
          .catch((err) => alert('上传失败: ' + err))
      }

      function uploadUrlEncoded() {
        const name = document.getElementById('fileName').value
        const content = document.getElementById('fileContent').value
        const data = new URLSearchParams()
        data.append('name', name)
        data.append('content', content)

        fetch('http://localhost:10086/hello', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
          },
          body: data
        })
          .then((res) => res.text())
          .then(alert)
          .catch((err) => alert('上传失败: ' + err))
      }
    </script>
  </body>
</html>
